package com.common.frame.extension


import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import retrofit2.HttpException
import java.net.ConnectException
import java.net.UnknownHostException
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * 有try-catch的携程调用
 */
fun CoroutineScope.launchCatch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    fail: (suspend CoroutineScope.(e: Throwable) -> Unit)? = null,
    block: suspend CoroutineScope.() -> Unit
) = launch(context, start) {
    try {
        this.block()
    } catch (e: Throwable) {
        e.printStackTrace()
        fail?.invoke(this, e)
    }
}

fun <T> Flow<T>.flowIO(): Flow<T> = flowOn(Dispatchers.IO)

fun <T> Flow<T>.catch(): Flow<T> = catch {
    it.handle()
}

fun Throwable.handle(callback: ((Throwable) -> Unit)? = null) {
    when (this) {
        is CancellationException -> {
        }
        is HttpException, is ConnectException, is UnknownHostException, is TimeoutCancellationException -> {

        }
        else -> {

        }
    }
    callback?.invoke(this)
}
